<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Game\EquipSnapshoot;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Support\Facades\DB;

class ItemController extends Controller
{
    public function snapshoot() //全服物品快照
    {
        $serverId = request()->get('gameArea');
        $equipIds = request()->get('equipId', []);
        $beginDateTime = request()->get('beginDateTime');
        $endDateTime = request()->get('endDateTime');

        $model = EquipSnapshoot::query();
        if (empty($equipIds)) {
            return ResponseUtil::error("请选择物品");
        }
        $model->whereIn('equip_id', $equipIds);

        if ($serverId !== null) {
            $model->where('server_id', $serverId);
        }

        // 计算天数差
        $startDate = strtotime($beginDateTime);
        $endDate = strtotime($endDateTime);
        $daysDiff = ceil(($endDate - $startDate) / (24 * 3600));

        if ($daysDiff > 1) {
            // 使用4小时间隔
            $xAxisData = [];
            $timePoints = [];
            
            // 将开始时间调整到最近的4小时整点
            $startHour = date('H', $startDate);
            $adjustedStartDate = $startDate - ($startHour % 4 * 3600) - date('i', $startDate) * 60 - date('s', $startDate);
            
            // 生成48个4小时间隔的点
            for ($i = 0; $i < 48; $i++) {
                $currentTime = $adjustedStartDate + ($i * 4 * 3600);
                $timeStr = date("Y-m-d H:00", $currentTime);
                $xAxisData[] = $timeStr;
                $timePoints[] = $timeStr;
            }

            MyLog::info('时间间隔数组'.json_encode($timePoints));
            $model->whereRaw("time >= ? AND time <= ?", [$beginDateTime, $endDateTime])
                  ->whereIn(DB::raw("DATE_FORMAT(time, '%Y-%m-%d %H:00')"), $timePoints);

            $results = $model->selectRaw('equip_id, equip_sum, DATE_FORMAT(time, "%Y-%m-%d %H:00") as hi')->get();
        } else {
            // 使用单日逻辑（30分钟间隔）
            $xAxisData = [];
            for ($hour = -8; $hour < 16; $hour += 0.5) {
                $xAxisData[] = date("H:i", $hour * 3600);
            }

            $model->whereRaw("SUBSTR(time,1,10) = ?", [date('Y-m-d', $startDate)])
                  ->whereIn(DB::raw("SUBSTR(time,12,5)"), $xAxisData);

            $results = $model->selectRaw('equip_id, equip_sum, SUBSTR(time,12,5) as hi')->get();
        }

        $data = [
            'xAxisData' => $xAxisData,
            'results' => $results,
        ];

        return ResponseUtil::success($data);
    }

}
